// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID

  try {
    // 检查用户是否已存在
    const userResult = await db.collection('users').doc(openid).get()
    
    // 更新用户数据
    const userData = {
      openid,
      nickname: event.nickname,
      avatarUrl: event.avatarUrl,
      updateTime: db.serverDate(),
    }

    // 如果用户存在，更新数据
    if (userResult.data) {
      await db.collection('users').doc(openid).update({
        data: userData
      })
    } else {
      // 如果用户不存在，创建新用户
      userData.createTime = db.serverDate()
      userData.highScore = 0
      userData.coins = 0
      userData.equipment = {
        egg: { level: 1 },
        bread: { level: 1 },
        coffee: { level: 1 }
      }
      await db.collection('users').doc(openid).set({
        data: userData
      })
    }

    return {
      success: true,
      data: userData
    }
  } catch (err) {
    // 如果是因为用户不存在导致的错误，创建新用户
    if (err.errCode === -1) {
      const userData = {
        openid,
        nickname: event.nickname,
        avatarUrl: event.avatarUrl,
        createTime: db.serverDate(),
        updateTime: db.serverDate(),
        highScore: 0,
        coins: 0,
        equipment: {
          egg: { level: 1 },
          bread: { level: 1 },
          coffee: { level: 1 }
        }
      }
      await db.collection('users').doc(openid).set({
        data: userData
      })
      return {
        success: true,
        data: userData
      }
    }
    
    return {
      success: false,
      error: err
    }
  }
}